package com.dlc.shop.platform.task;

import cn.binarywang.wx.miniapp.api.WxMaOrderShippingService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaOrderShippingServiceImpl;
import cn.binarywang.wx.miniapp.bean.shop.request.shipping.OrderKeyBean;
import cn.binarywang.wx.miniapp.bean.shop.request.shipping.PayerBean;
import cn.binarywang.wx.miniapp.bean.shop.request.shipping.ShippingListBean;
import cn.binarywang.wx.miniapp.bean.shop.request.shipping.WxMaOrderShippingInfoUploadRequest;
import cn.binarywang.wx.miniapp.bean.shop.response.WxMaOrderShippingInfoBaseResponse;
import cn.binarywang.wx.miniapp.bean.shop.response.WxMaOrderShippingInfoGetListResponse;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.dlc.shop.bean.enums.DeliveryType;
import com.dlc.shop.bean.model.Order;
import com.dlc.shop.bean.model.OrderItem;
import com.dlc.shop.bean.model.PayInfo;
import com.dlc.shop.common.util.Json;
import com.dlc.shop.config.WxConfig;
import com.dlc.shop.service.OrderService;
import com.dlc.shop.service.PayInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Objects;

/**
 * @author yami
 */
@Slf4j
@Component
@AllArgsConstructor
public class OrderDeliveryTask {

    private final WxConfig wxConfig;
    private final PayInfoService payInfoService;
    private final ApplicationEventPublisher eventPublisher;
    private final OrderService orderService;


    /**
     * 小程序发货虚拟订单和自提订单
     */
    @XxlJob("wxAppShipment")
    public void wxAppShipment() {
        XxlJobHelper.log("小程序发货定时任务");
        Boolean managed = wxConfig.getTradeManaged();
        if (managed) {
            WxMaOrderShippingInfoGetListResponse response = wxConfig.getOrderIdList();
            if (CollectionUtil.isNotEmpty(response.getOrderList())) {
                for (WxMaOrderShippingInfoBaseResponse.Order wxOrder : response.getOrderList()) {
                    WxMaOrderShippingInfoUploadRequest request = new WxMaOrderShippingInfoUploadRequest();
                    OrderKeyBean orderKey = new OrderKeyBean();
                    orderKey.setOrderNumberType(2);
                    orderKey.setTransactionId(wxOrder.getTransactionId());
                    request.setOrderKey(orderKey);
                    request.setDeliveryMode(1);
                    PayInfo payInfo = payInfoService.getOne(new LambdaQueryWrapper<PayInfo>().eq(PayInfo::getPayNo, wxOrder.getMerchantTradeNo()));
                    if (Objects.isNull(payInfo)) {
                        continue;
                    }
                    String[] orderIds = payInfo.getOrderNumbers().split(",");
                    // 因为只获取虚拟订单和自提订单，所以其实只有一个orderId
                    Order order = orderService.getOrderAndOrderItemByOrderNumber(orderIds[0]);
                    if (Objects.isNull(order)) {
                        continue;
                    }
                    // 不是虚拟订单或自提订单，不需要定时任务发货
                    if (order.getDvyType().equals(DeliveryType.STATION.getValue())) {
                        request.setLogisticsType(4);
                    } else if (order.getOrderMold() == 1) {
                        request.setLogisticsType(3);
                    } else {
                        continue;
                    }
                    ShippingListBean shippingListBean = new ShippingListBean();
                    String itemDesc = "";
                    for (OrderItem orderItem : order.getOrderItems()) {
                        itemDesc += orderItem.getProdName() + "*" + orderItem.getProdCount() + "    ";
                    }
                    shippingListBean.setItemDesc(itemDesc);
                    request.setShippingList(Collections.singletonList(shippingListBean));
                    DateFormat dft = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
                    request.setUploadTime(dft.format(new Date()));
                    PayerBean payerBean = new PayerBean();
//                    eventPublisher.publishEvent(new AppConnectEvent(order.getUserId(), payerBean));
                    payerBean.setOpenid(payInfo.getBizUserId());
                    request.setPayer(payerBean);
                    try {
                        WxMaService wxMaService = wxConfig.getWxMaService();
                        WxMaOrderShippingService wxMaOrderShippingService = new WxMaOrderShippingServiceImpl(wxMaService);
                        XxlJobHelper.log("小程序发货录入的参数：" + Json.toJsonString(request));
                        wxMaOrderShippingService.upload(request);
                    } catch (WxErrorException wxErrorException) {
                        wxErrorException.printStackTrace();
                        XxlJobHelper.log("订单id为"+ order.getOrderId() +"的小程序发货错误信息：" + wxErrorException.getError().getErrorMsg());
                    }
                }
            }
        }
    }

}
